package com.spring.shopping.controller;

import com.spring.shopping.entity.*;
import com.spring.shopping.service.CartService;
import com.spring.shopping.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/*
 * @Coding By ZTK:
 */


@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private CartService cartService;

    @GetMapping("/list")
    public String orderList(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            Model model,
            HttpSession session) {

        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            return "redirect:/user/login";
        }

        int offset = (page - 1) * size;

        List<Order> orders = orderService.getOrdersByUserId(user.getId(), offset, size);
        int totalOrders = orderService.countOrdersByUserId(user.getId());

        int totalPages = (int) Math.ceil((double) totalOrders / size);

        model.addAttribute("orders", orders);
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("totalOrders", totalOrders);

        return "order/list";
    }

    @GetMapping("/create")
    public String showOrderForm(@RequestParam("cartIds") String cartIdsStr,
                                HttpSession session, Model model) {
        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            return "redirect:/user/login";
        }

        List<Integer> cartIds = Arrays.stream(cartIdsStr.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        List<CartItem> cartItems = cartService.getCartItemsByIds(user.getId(), cartIds);
        if (cartItems.isEmpty()) {
            return "redirect:/cart/view";
        }

        BigDecimal totalAmount = BigDecimal.ZERO;
        for (CartItem item : cartItems) {
            totalAmount = totalAmount.add(BigDecimal.valueOf(item.getProduct().getPrice()).multiply(BigDecimal.valueOf(item.getQuantity())));
        }

        model.addAttribute("cartItems", cartItems);
        model.addAttribute("totalAmount", totalAmount);
        model.addAttribute("cartIds", cartIdsStr);
        return "order/create";
    }

    @PostMapping("/create")
    public String createOrder(@RequestParam("cartIds") String cartIdsStr,
                              @RequestParam("receiverName") String receiverName,
                              @RequestParam("receiverAddress") String receiverAddress,
                              @RequestParam("receiverPhone") String receiverPhone,
                              HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            return "redirect:/user/login";
        }

        List<Integer> cartIds = Arrays.stream(cartIdsStr.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        List<CartItem> cartItems = cartService.getCartItemsByIds(user.getId(), cartIds);
        if (cartItems.isEmpty()) {
            return "redirect:/cart/view";
        }

        Order order = orderService.createOrder(
                user.getId(),
                cartItems,
                receiverName,
                receiverAddress,
                receiverPhone
        );

        for (CartItem item : cartItems) {
            cartService.removeFromCart(item.getCartId());
        }

        return "redirect:/order/detail/" + order.getId();
    }

    @GetMapping("/detail/{id}")
    public String orderDetail(@PathVariable Integer id, Model model, HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            return "redirect:/user/login";
        }

        Order order = orderService.getOrderById(id);
        if (order == null || !order.getUserId().equals(user.getId())) {
            return "redirect:/order/list";
        }

        model.addAttribute("order", order);
        return "order/detail";
    }

    @PostMapping("/pay/{id}")
    public String payOrder(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        if (user == null) return "redirect:/user/login";

        orderService.updateOrderStatus(id, "已支付");
        return "redirect:/order/success/" + id;
    }

    @GetMapping("/success/{id}")
    public String paymentSuccess(@PathVariable Integer id, Model model, HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            return "redirect:/user/login";
        }

        Order order = orderService.getOrderById(id);
        if (order == null || !order.getUserId().equals(user.getId())) {
            return "redirect:/order/list";
        }

        model.addAttribute("order", order);
        return "order/success";
    }
}
